package com.starblink.mine.personhome.ui.wishlist.ui.wishlistboards.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.rocketreserver.FetchWishListsByAccountIdV2Query
import com.starblink.rocketreserver.type.WishListsReq
import kotlinx.coroutines.launch

class WishlistBoardsVM : BaseViewModel() {
    var accountId: String = ""
    var curPageNo = 0 // 当前页数，默认是0
    private val listResponse: ListResponse = ListResponse()
    var listResponseLiveData: MutableLiveData<ListResponse> =
        MutableLiveData()

    /**
     * 保存服务器返回数据
     */
    inner class ListResponse {
        val totalList = ArrayList<FetchWishListsByAccountIdV2Query.WishList>() // 保存全部列表数据
        lateinit var pageList: List<FetchWishListsByAccountIdV2Query.WishList> // 保存单页请求数据
        var refresh: Boolean = true // true-下拉刷新，false表示加载更多
    }

    /**
     * 获取客态用户心愿单列表
     * @param refresh: true表示请求首页，false表示请求下一页
     */
    fun getWishLists(refresh: Boolean = true) {
        val requestPageNo = if (refresh) 1 else curPageNo + 1


        viewModelScope.launch {
            val response = SkGqlClient.skQuery(
                FetchWishListsByAccountIdV2Query(
                    wishListsReq = WishListsReq(
                        accountId = accountId,
                        pageNo = Optional.present(requestPageNo),
                        pageSize = Optional.present(PAGE_SIZE),
//                        lastId = Optional.present(if (refresh) null else listResponseLiveData.value?.totalList?.last()?.wishListF?.id)
                    )
                )
            )
            if (response?.data?.fetchWishListsByAccountIdV2 != null) {
                val wishlists = response?.data?.fetchWishListsByAccountIdV2!!.wishLists ?: emptyList()
                curPageNo = requestPageNo
                listResponse.apply {
                    pageList = wishlists
                    this.refresh = refresh
                    if (refresh) {
                        totalList.clear()
                    }
                    totalList.addAll(pageList)
                }
                listResponseLiveData.postValue(listResponse)
            } else {
                // 加载失败，提示用户（已toast提示）
                loadError(null)
            }
        }
    }

    companion object {
        const val PAGE_SIZE = 20
    }
}